/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.ajz.web;

import com.github.sd4324530.fastweixin.company.api.config.QYAPIConfig;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.io.FileUtils;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.common.web.http.ServletUtils;
import com.jeesite.modules.ajz.entity.AjzCompanyInfo;
import com.jeesite.modules.ajz.entity.AjzRecord;
import com.jeesite.modules.ajz.service.AjzCompanyInfoService;
import com.jeesite.modules.ajz.service.AjzRecordService;
import com.jeesite.modules.sys.entity.Employee;
import com.jeesite.modules.sys.service.EmployeeService;
import com.jeesite.modules.sys.wx.qy.py.WeixinJSSDKSignUtil;
import com.jeesite.modules.sys.wx.qy.util.DloadImgUtil;
import com.jeesite.modules.sys.wx.qy.util.QyConfigUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 企业信息表Controller
 * @author cww
 * @version 2019-01-11
 */
@Controller
@RequestMapping(value = "${adminPath}/ajz/ajzCompanyInfo")
public class AjzCompanyInfoController extends BaseController {

	@Autowired
	private AjzCompanyInfoService ajzCompanyInfoService;
	@Autowired
	private EmployeeService employeeService;
	@Autowired
	private AjzRecordService ajzRecordService;
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public AjzCompanyInfo get(String id, boolean isNewRecord) {
		return ajzCompanyInfoService.get(id, isNewRecord);
	}

	@RequiresPermissions("sys:empUser:view")
	@RequestMapping(value = "index")
	public String index(AjzCompanyInfo ajzCompanyInfo, Model model) {
		return "modules/ajz/ajzCompanyIndex";
	}

	/**
	 * 查询列表
	 */
	@RequiresPermissions("ajz:ajzCompanyInfo:view")
	@RequestMapping(value = {"list", ""})
	public String list(AjzCompanyInfo ajzCompanyInfo, Model model) {
		model.addAttribute("ajzCompanyInfo", ajzCompanyInfo);
		return "modules/ajz/ajzCompanyInfoList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("ajz:ajzCompanyInfo:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<AjzCompanyInfo> listData(AjzCompanyInfo ajzCompanyInfo, HttpServletRequest request, HttpServletResponse response) {
		ajzCompanyInfo.setPage(new Page<>(request, response));
		Page<AjzCompanyInfo> page = ajzCompanyInfoService.findPage(ajzCompanyInfo); 
		return page;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("ajz:ajzCompanyInfo:view")
	@RequestMapping(value = "form")
	public String form(AjzCompanyInfo ajzCompanyInfo, Model model) {
		model.addAttribute("ajzCompanyInfo", ajzCompanyInfo);
		return "modules/ajz/ajzCompanyInfoForm";
	}

	/**
	 * 保存企业信息表
	 */
	@RequiresPermissions("ajz:ajzCompanyInfo:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated AjzCompanyInfo ajzCompanyInfo) {
		ajzCompanyInfoService.save(ajzCompanyInfo);
		return renderResult(Global.TRUE, text("保存企业信息表成功！"));
	}
	
	/**
	 * 删除企业信息表
	 */
	@RequiresPermissions("ajz:ajzCompanyInfo:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(AjzCompanyInfo ajzCompanyInfo) {
		ajzCompanyInfoService.delete(ajzCompanyInfo);
		return renderResult(Global.TRUE, text("删除企业信息表成功！"));
	}


//	/**
//	 * 下载导入用户数据模板
//	 */
//	@RequiresPermissions("ajz:ajzCompanyInfo:view")
//	@RequestMapping(value = "importTemplate")
//	public void importTemplate(HttpServletResponse response) {
//		AjzCompanyInfo companyInfo = new AjzCompanyInfo();
//		List<AjzCompanyInfo> list = ListUtils.newArrayList(companyInfo);
//		String fileName = "企业数据模板.xlsx";
//		try(ExcelExport ee = new ExcelExport("企业数据", AjzCompanyInfoVO.class, ExcelField.Type.IMPORT)){
//			ee.setDataList(list).write(response, fileName);
//		}
//	}

	/**
	 * 导入用户数据
	 */
	@ResponseBody
	@RequiresPermissions("ajz:ajzCompanyInfo:edit")
	@PostMapping(value = "importData")
	public String importData(MultipartFile file, String updateSupport) {
		try {
			boolean isUpdateSupport = Global.YES.equals(updateSupport);
			ajzCompanyInfoService.updateVariable();
			String message = ajzCompanyInfoService.importData(file, isUpdateSupport);
			return renderResult(Global.TRUE, "posfull:"+message);
		} catch (Exception ex) {
			return renderResult(Global.FALSE, "posfull:"+ex.getMessage());
		}
	}

	/**
	 * 下载导入企业数据模板
	 */
	@RequiresPermissions("ajz:ajzCompanyInfo:view")
	@RequestMapping(value = "importTemplate")
	public void shipinTemplate(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "公司模板.xlsx";
			String realPath = request.getSession().getServletContext().getRealPath("/downLoad/公司模板.xlsx");
			downLoadFile(realPath, response, fileName);
//			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
		}
//		return "redirect:" + adminPath + "/ajz/ajzBaseinfo/list?repage";
	}

	/**
	 * 文件下载
	 *
	 * @param filePath
	 * @param response
	 * @param filename
	 */
	@SuppressWarnings("resource")
	public void downLoadFile(String filePath, HttpServletResponse response, String filename) {
		BufferedOutputStream bufferOut = null;
		BufferedInputStream bufferIn = null;
		try {
			bufferIn = new BufferedInputStream(new FileInputStream(filePath));
			bufferOut = new BufferedOutputStream(response.getOutputStream());
			response.setCharacterEncoding("UTF-8");
			response.setHeader("Content-disposition", "attachment; filename=" + new String(filename.getBytes("UTF-8"), "iso8859-1"));
			byte[] Byte = new byte[1024];
			int len = 0;
			while (-1 != (len = bufferIn.read(Byte))) {
				bufferOut.write(Byte, 0, len);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != bufferOut) {
				try {
					bufferOut.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != bufferIn) {
				try {
					bufferIn.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}


	//测试
	@RequestMapping(value = "test")
	public String test(AjzCompanyInfo ajzCompanyInfo, Model model) {
		return "modules/ajz/ajzCompanyIndex";
	}

	//获取用户信息后跳转到类别选择页面
	@RequestMapping(value = "ajzType")
	public String ajzType(AjzCompanyInfo ajzCompanyInfo,HttpServletRequest request,HttpServletResponse response, Model model) {
		String userCode = QyConfigUtil.getUserId(request,response);
		Employee user1 = employeeService.get(userCode);

		model.addAttribute("userId",userCode);
		model.addAttribute("officeId",user1.getOffice().getId());

		return "modules/ajz/staff";
	}

	//获取用户信息后跳转到添加商家页面
	@RequestMapping(value = "chooice")
	public String chooice(AjzCompanyInfo ajzCompanyInfo,HttpServletRequest request,HttpServletResponse response, Model model) {
		String userCode = QyConfigUtil.getUserId(request,response);
		Employee user1 = employeeService.get(userCode);

		model.addAttribute("userId",userCode);
		model.addAttribute("officeId",user1.getOffice().getId());

		return "modules/ajz/staff3";
	}

//	商家展示页面
	@RequestMapping(value = "ajzList")
	public String ajzList(AjzCompanyInfo ajzCompanyInfo,HttpServletRequest request,HttpServletResponse response, Model model) {

		ajzCompanyInfo.setPage(new Page<>(request, response));
		Page<AjzCompanyInfo> page = ajzCompanyInfoService.findPage(ajzCompanyInfo);

		System.out.println(page.getList().size());
		model.addAttribute("userId",request.getParameter("userId"));
		model.addAttribute("officeId",request.getParameter("officeId"));
		model.addAttribute("ajzType",request.getParameter("ajzType"));
		model.addAttribute("page",page);
		model.addAttribute("hwzp",request.getParameter("hwzp"));
		model.addAttribute("pageno","1");
		model.addAttribute("pages","1");
		model.addAttribute("status","1");
		model.addAttribute("ajzCount","2");
		return "modules/ajz/e_query";
	}

//提交记录页面
	@RequestMapping(value = "record")
	public String record(AjzCompanyInfo ajzCompanyInfo,HttpServletRequest request,HttpServletResponse response, Model model) {

		String ajzCompanyInfoId = request.getParameter("id");
		model.addAttribute("userId",request.getParameter("userId"));
		model.addAttribute("officeId",request.getParameter("officeId"));
		model.addAttribute("ajzType",request.getParameter("ajzType"));
		model.addAttribute("hwzp",request.getParameter("hwzp"));
		model.addAttribute("pageno","1");
		model.addAttribute("pages","1");
		model.addAttribute("status","1");
		model.addAttribute("ajzCount","2");

		String userCode = QyConfigUtil.getUserId(request,response);
		Employee user1 = employeeService.get(userCode);
		model.addAttribute("user",user1);

		ajzCompanyInfo = ajzCompanyInfoService.get(ajzCompanyInfoId);
		model.addAttribute("ajzCompanyInfo",ajzCompanyInfo);

		QYAPIConfig qyapiConfig = QyConfigUtil.getQYAPIConfig();
		String jsapi_ticket = qyapiConfig.getJsApiTicket();

		String queryString = request.getQueryString();
		String url2 = "http://" + request.getServerName() // 服务器地址
				+ request.getContextPath() // 项目名称
				+ request.getServletPath(); // 请求页面或其他地址

		if (queryString != null) {
			url2 += "?" + queryString;
		}
// 获得微信jssdk签名等
		Map<String, String> sign = WeixinJSSDKSignUtil.sign(jsapi_ticket, url2);
//
		model.addAttribute("appId", QyConfigUtil.apiConfig.getCorpid());
		model.addAttribute("nonceStr", sign.get("nonceStr"));
		model.addAttribute("timestamp", sign.get("timestamp"));
		model.addAttribute("signature", sign.get("signature"));

		return "modules/ajz/table";
	}

	//记录提交，展示记录页面
	@RequestMapping(value = "recordCommit")
	public String recordCommit(AjzCompanyInfo ajzCompanyInfo,HttpServletRequest request,HttpServletResponse response, Model model) {


		String ajzType = request.getParameter("ajzType");
		String userId = request.getParameter("userId");
		String ajzCompanyInfoId = request.getParameter("ajzCompanyInfoId");


		model.addAttribute("userId",userId);
		model.addAttribute("officeId",request.getParameter("officeId"));
		model.addAttribute("ajzCompanyInfoId",ajzCompanyInfoId);
		model.addAttribute("ajzType",ajzType);
		model.addAttribute("hwzp",request.getParameter("hwzp"));
		model.addAttribute("pageno","1");
		model.addAttribute("pages","1");
		model.addAttribute("status","1");
		model.addAttribute("ajzCount","2");

		//处理文件路径
		//创建保存在文件管理器中的文件路径
		String filePath = Global.getUserfilesBaseDir(userId + File.separator + "images" + File.separator + "photo" + File.separator
				+ DateUtils.getYear() + File.separator
				+ DateUtils.getMonth() + File.separator);
		//创建保存数据库的图片路径
		String savePath = request.getContextPath() + userId + "/images/photo/"
				+ DateUtils.getYear() + "/"
				+ DateUtils.getMonth() + "/";
		FileUtils.createDirectory(filePath);
		//处理签名
		String hotelDzqm = request.getParameter("hotelDzqm");
		String staffDzqm = request.getParameter("staffDzqm");
		String staffDzqm2 = request.getParameter("staffDzqm2");
		String accessToken = QyConfigUtil.getAccessToken();
		if(StringUtils.isNotBlank(hotelDzqm)){
			hotelDzqm = DloadImgUtil.GenerateImage(hotelDzqm,filePath,savePath);
		}
		if(StringUtils.isNotBlank(staffDzqm)){
			staffDzqm = DloadImgUtil.GenerateImage(staffDzqm,filePath,savePath);
		}
		if(StringUtils.isNotBlank(staffDzqm2)){
			staffDzqm2 = DloadImgUtil.GenerateImage(staffDzqm2,filePath,savePath);
		}
		//处理隐患
		String danUrls = request.getParameter("danUrls");
		if(StringUtils.isNotBlank(danUrls)){
			danUrls = DloadImgUtil.downloadMedias(accessToken,danUrls,savePath,filePath);
		}


		AjzRecord ajzRecord = new AjzRecord();
		ajzRecord.setDangerPic(danUrls);
		ajzRecord.setContactorSign(hotelDzqm);
		ajzRecord.setWorkerSign1(staffDzqm);
		ajzRecord.setWorkerSign2(staffDzqm2);
		ajzRecord.setBaseId(ajzCompanyInfoId);
//		ajzRecord.setcre
		ajzRecord.setBaseType(ajzType);
		ajzRecord.setIsNewRecord(true);
		ajzRecordService.save(ajzRecord);


		List<AjzRecord> list = ajzRecordService.findList(new AjzRecord());
		model.addAttribute("list",list);
		return "modules/ajz/staff2";
	}

	@RequestMapping(value = "recordList")
	public String recordList(AjzCompanyInfo ajzCompanyInfo,HttpServletRequest request,HttpServletResponse response, Model model) {
		System.out.println("1");
		List<AjzRecord> list = ajzRecordService.findList(new AjzRecord());
		model.addAttribute("list",list);
		String userCode = QyConfigUtil.getUserId(request,response);

		Employee user1 = employeeService.get(userCode);

		model.addAttribute("userId",userCode);
		model.addAttribute("officeId",user1.getOffice().getId());

		return "modules/ajz/staff2";

	}

	//展示单跳记录页面
	@RequestMapping(value = "recordShow")
	public String recordShow(AjzCompanyInfo ajzCompanyInfo,HttpServletRequest request,HttpServletResponse response, Model model) {
		String ajzType = request.getParameter("ajzType");
		String userId = request.getParameter("userId");
		String ajzCompanyInfoId = request.getParameter("ajzCompanyInfoId");
		String ajzRecordId = request.getParameter("ajzRecordId");

		AjzRecord ajzRecord = ajzRecordService.get(ajzRecordId);
		ajzCompanyInfo = ajzCompanyInfoService.get(ajzCompanyInfoId);

		model.addAttribute("ajzRecord",ajzRecord);
		model.addAttribute("ajzCompanyInfo",ajzCompanyInfo);
		//处理商家签字图片,获取页面展示路径
		String hotelDzqm = DloadImgUtil.getGenerateImage(ajzRecord.getContactorSign());
		String staffDzqm1 = DloadImgUtil.getGenerateImage(ajzRecord.getWorkerSign1());
		String staffDzqm2 = DloadImgUtil.getGenerateImage(ajzRecord.getWorkerSign2());
		model.addAttribute("hotelDzqm",hotelDzqm);
		model.addAttribute("staffDzqm1",staffDzqm1);
		model.addAttribute("staffDzqm2",staffDzqm2);
		//处理隐患图片,获取页面展示路径
		String dangerUrls = ajzRecord.getDangerPic();
		List dangerList = null;
		if (!StringUtils.isBlank(dangerUrls)) {
			String[] dangersplit = StringUtils.split(dangerUrls, "|");
			for(int i=0;i<dangersplit.length;i++){
				dangersplit[i] = "/userfiles/"+dangersplit[i];
			}
			dangerList = Arrays.asList(dangersplit);
		}
		model.addAttribute("dangerList",dangerList);

		return "modules/ajz/tableView";
	}

	//添加商家的信息提交页面
	@RequestMapping(value = "addEnterprise")
	public String addEnterprise(AjzCompanyInfo ajzCompanyInfo,HttpServletRequest request,HttpServletResponse response, Model model) {

		model.addAttribute("userId",request.getParameter("userId"));
		model.addAttribute("ajzType",request.getParameter("ajzType"));
		model.addAttribute("officeId",request.getParameter("officeId"));

		return "modules/ajz/staff31addaqsc";
	}

	//添加商家的信息
	@RequestMapping(value = "addQYInfo")
	public String addQYInfo(AjzCompanyInfo ajzCompanyInfo,HttpServletRequest request,HttpServletResponse response, Model model) {

		String userId = request.getParameter("userId");
		model.addAttribute("userId",userId);
		model.addAttribute("ajzType",request.getParameter("ajzType"));
		model.addAttribute("officeId",request.getParameter("officeId"));
		ajzCompanyInfo.setLegalPerson(request.getParameter("legalPerson"));
		ajzCompanyInfo.setLegalPersonTel(request.getParameter("legalPersonTel"));
		ajzCompanyInfo.setContactPerson(request.getParameter("contactPerson"));
		ajzCompanyInfo.setContactPersonTel(request.getParameter("contactPersonTel"));
		ajzCompanyInfo.setEnterpriseName(request.getParameter("enterpriseName"));
		ajzCompanyInfo.setPost(request.getParameter("post"));
		ajzCompanyInfo.setAddr(request.getParameter("addr"));
		ajzCompanyInfo.setBuinessContent(request.getParameter("buinessContent"));
		ajzCompanyInfo.setEnterpriseType(request.getParameter("enterpriseType"));
		ajzCompanyInfo.setFloorCount(request.getParameter("floorCount"));
		ajzCompanyInfo.setEmpCount(request.getParameter("empCount"));
		ajzCompanyInfo.setRemarks(request.getParameter("remarks"));
		ajzCompanyInfo.setYearValue(request.getParameter("yearValue"));
		ajzCompanyInfo.setScale(request.getParameter("scale"));
		ajzCompanyInfo.setStatus("0");
		ajzCompanyInfo.setDangerLev(request.getParameter("dangerLev"));
		ajzCompanyInfo.setIsNewRecord(true);
		ajzCompanyInfoService.save(ajzCompanyInfo);


		System.out.println(Global.getFrontPath());
		System.out.println(Global.getUserfilesBaseDir("a"));
		System.out.println("key:"+Global.getConfig("adminPath"));
		System.out.println(Global.getProperty(adminPath));
		String queryString = request.getQueryString();
		queryString = queryString == null ? "" : "?" + queryString;
		System.out.println("cont:"+request.getContextPath());
		System.out.println(request.getQueryString());
		System.out.println(request.getRequestURI());
		System.out.println(request.getServletPath());
		System.out.println(request.isRequestedSessionIdFromURL());
		System.out.println(request.getRequestDispatcher(""));
		System.out.println(request.getLocalAddr());

		ServletUtils.redirectUrl(request, response, adminPath + "/ajz/ajzCompanyInfoController/ajzType" + queryString);

		return null;
	}

}